package com.jc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class PostgreSQLDelete {
    public static void main(String[] args) {
        String url = null;
        String user = null;
        String password = null;
        int affectedRows = 0;
        String sql = "delete from users where id = ?";

        // 读取数据库配置（适配资源目录）
        try (InputStream file = PostgreSQLDelete.class.getClassLoader().getResourceAsStream("db.properties")) {
            if (file == null) {
                System.out.println("错误：未找到 db.properties 文件，请放在 src/main/resources 目录下");
                return;
            }
            Properties p = new Properties();
            p.load(file);
            url = p.getProperty("url");
            user = p.getProperty("user");
            password = p.getProperty("password");
        } catch (IOException e) {
            System.out.println("配置文件读取失败：" + e.getMessage());
            return;
        }

        // 校验配置完整性
        if (url == null || user == null || password == null) {
            System.out.println("错误：db.properties 中缺少 url、user 或 password 配置");
            return;
        }

        // 注册 PostgreSQL 驱动
        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("错误：未找到 PostgreSQL 驱动，请检查依赖");
            return;
        }

        // 执行删除操作
        try (Connection conn = DriverManager.getConnection(url, user, password);
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setInt(1, 1); // 删除 id=1 的记录
            affectedRows = ps.executeUpdate();
            System.out.println("删除成功，影响行数：" + affectedRows);

        } catch (SQLException e) {
            System.out.println("删除失败：" + e.getMessage());
            System.out.println("错误码：" + e.getErrorCode());
        }
    }
}